package com.ecmap.hongyun.commons.interceptor;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.AbstractView;
/**
 * 自定义Excel视图, 将model里的数据交给jxls模板渲染
 * @author wubz
 *
 */
public class JxlsExcelView extends AbstractView{
	
	protected Logger log = Logger.getLogger(this.getClass());
	
	public JxlsExcelView() {
		setContentType("application/vnd.ms-excel");
		
	}
	
	@Override
	protected void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.reset();
		response.setContentType(getContentType());
		
		String xlsTemplateFileName = (String) model.get("inputFile");
		String outputFileName = (String) model.get("outputFile");
		
		File file = new File(request.getSession().getServletContext().getRealPath("") + xlsTemplateFileName);
		if(!file.exists()){
			throw new Exception("excel template file \"" + xlsTemplateFileName + "\" is not exist");
		}		
		Map beans = new HashMap();		
		beans.put("list", model.get("excelList"));
		
		InputStream in = null;
		HSSFWorkbook workbook;
		try {
			in = new FileInputStream(file);
			
			XLSTransformer transformer = new XLSTransformer();
											
			workbook = transformer.transformXLS(in, beans);
						
			outputFileName = outputFileName == null ? "_" + System.currentTimeMillis() : outputFileName;
			
			outputFileName = new String(outputFileName.getBytes("gb2312"),"iso8859-1");
			
			response.setHeader("Content-Disposition", "attachment; filename=\"" + outputFileName + ".xls\"");
			
			OutputStream out = response.getOutputStream();
			
			workbook.write(out);
			
			out.flush();  
			
		} finally {
			if (in != null) {
				in.close();
			}
		}
		
		
		
	}



}
